package drds.datasource.connection_pool.util;


import drds.datasource.connection_pool.api.SqlException;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

public class MySqlUtils {


    static Class<?> connectionImplClass = null;
    static Method getIdMethod = null;
    static boolean getIdMethodError = false;


    public static Long getId(Connection connection) {
        if (connection == null) {
            return null;
        }
        Class<?> clazz = connection.getClass();
        if (connectionImplClass == null) {
            if (clazz.getName().equals("com.mysql.jdbc.ConnectionImpl")) {
                connectionImplClass = clazz;
            } else if (clazz.getName().equals("com.mysql.jdbc.Connection")) { // mysql 5.0.x
                connectionImplClass = clazz;
            } else if (clazz.getName().equals("com.mysql.cj.jdbc.ConnectionImpl")) { // mysql 5.0.x
                connectionImplClass = clazz;
            } else if (clazz.getSuperclass().getName().equals("com.mysql.jdbc.ConnectionImpl")) {
                connectionImplClass = clazz.getSuperclass();
            }
        }

        if (connectionImplClass == clazz || connectionImplClass == clazz.getSuperclass()) {
            try {
                if (getIdMethod == null && !getIdMethodError) {
                    Method method = connectionImplClass.getDeclaredMethod("getId");
                    method.setAccessible(true);
                    getIdMethod = method;
                }
                return (Long) getIdMethod.invoke(connection);
            } catch (Throwable ex) {
                getIdMethodError = true;
            }
        }

        return null;
    }

    public static String buildKillQuerySql(Connection connection, SQLException e) throws SqlException {
        Long threadId = getId(connection);
        if (threadId == null) {
            return null;
        }

        return "KILL QUERY " + threadId;

    }


}
